//
//  PxHomeViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxAVCaptureViewController.h"

@implementation PxAVCaptureViewController {
    NSArray *compArray;
    NSString *companyCode;
    NSString *expressCompany;
    int type;
}

static const char *kScanQRCodeQueueName = "ScanQRCodeQueue";

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        compArray = [PxGlobal getData:COMPANY_INFO];
        if (compArray.count > 0) {
            companyCode = compArray[0][@"value"];
            expressCompany = compArray[0][@"label"];
        } else {
            companyCode = @"error";
            expressCompany = @"error";
        }
        type = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super setLogoTitleViewWithTitle:@"扫描上架"];
    [self.contentView setScrollEnabled:NO];
    UIButton *btn = [PxWidgetCreater customerButton];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn setTitle:expressCompany];
    [btn setImage:[UIImage imageNamed:@"Images/ss-arrow"]];
    btn.frame = CGRectMake(0, 0, self.view.width, [PxGlobal getCustomerHeight:42]);
    [self.view addSubview:btn];
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 85, 0, 0);
    btn.backgroundColor = [UIColor colorWithHTMLStr:@"000000"];
    [btn setSelector:@selector(changeComp) withTarget:self];
    btn.hidden = YES;
    self.headerBtn = btn;
    
    CGRect scanCrop = CGRectMake([PxGlobal getCustomerWidth:45], [PxGlobal getCustomerHeight:100], [PxGlobal getCustomerWidth:230], [PxGlobal getCustomerHeight:165]);
    _readerView = [[PxReaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - btn.height)];
    _readerView.scanRect = scanCrop;
    _readerView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_readerView];
    
    [self setRightBtn:@"手动"];
}

-(void)setRightBtn:(NSString *) title
{
    UIButton *navBarRightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [navBarRightButton addTarget:self action:@selector(navBarRightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [navBarRightButton setContentMode:UIViewContentModeCenter];
    
    [navBarRightButton setTitle:title];
    
    navBarRightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    UIColor *color1 = [UIColor colorWithHTMLStr:@"ff4e08"];
    [navBarRightButton setTitleColor:color1 forState:UIControlStateNormal];
    
    UIBarButtonItem *rightButtonItem=[[UIBarButtonItem alloc] initWithCustomView:navBarRightButton];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    if([LLYTSmallUtil iOSBigVersion] >= 6.5)
        negativeSpacer.width = -9;// it was -6 in iOS 6
    else
        negativeSpacer.width = 1;
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer,rightButtonItem/*this will be the button which u actually need*/, nil] animated:NO];
}

- (void)navBarRightBtnAction
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请输入运单号"] preferredStyle: UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"请输入运单号...";
    }];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        UITextField *textField = alertController.textFields.firstObject;
        NSString *value = textField.text;
        if (value && value.length > 0) {
            [self gotoPage:value];
        } else {
            [self showMSG:@"运单号不能为空" withType:1];
        }
    }];
    UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        
    }];
    [alertController addAction:OKAction];
    [alertController addAction:CancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (BOOL)startReading
{
    _isReading = YES;
    // 获取 AVCaptureDevice 实例
    NSError * error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 初始化输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    // 创建会话
    self.session = [[AVCaptureSession alloc] init];
    // 添加输入流
    [self.session addInput:input];
    // 初始化输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    // 添加输出流
    [self.session addOutput:captureMetadataOutput];
    
    // 创建dispatch queue.
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create(kScanQRCodeQueueName, NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    // 设置元数据类型 AVMetadataObjectTypeQRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code,
        AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code, nil]];
    
    // 创建输出对象
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:_readerView.bounds];
    [self.view.layer insertSublayer:_videoPreviewLayer atIndex:0];
//    [_readerView.layer insertSublayer:_videoPreviewLayer atIndex:10];
//    [_readerView.layer addSublayer:_videoPreviewLayer];
    
    //用户是否允许启用摄像头
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted)
        {
            //Granted access to mediaType
            [self.session startRunning];
        }
        else
        {
            //Not granted access to mediaType
            dispatch_async(dispatch_get_main_queue(), ^{
                [[[UIAlertView alloc] initWithTitle:@"AVCam!"
                                            message:@"AVCam doesn't have permission to use Camera, please change privacy settings"
                                           delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil] show];
            });
        }
    }];
    
    return YES;
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result = metadataObj.stringValue;
        [self performSelectorOnMainThread:@selector(reportScanResult:) withObject:result waitUntilDone:NO];
    }
}

-(void)gotoPage:(NSString *)waybillNo
{
    if (type == 0) {
        [self popToLastControllerWithIncomingParam:@{@"waybillNo":waybillNo,
                                                     @"companyCode":companyCode,
                                                     @"expressCompany":expressCompany}];
    } else {
        [self pushViewController:@"PxWayBillSaveViewController" withIncomingParam:@{@"waybillNo":waybillNo,
                                                                                    @"companyCode":companyCode,
                                                                                    @"expressCompany":expressCompany}];
    }
}

- (void)reportScanResult:(NSString *)result
{
    LLDLog(@"result:%@", result);
    if (!_isReading)
        return;
    _isReading = NO;
    [self gotoPage:result];
}

- (void)stopReading
{
    // 停止会话
    [self.session stopRunning];
    self.session = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    type = [self.incomingParam[@"type"] intValue];
    NSString *title = self.incomingParam[@"title"];
    if (title && title.length > 0)
        [self setLogoTitleViewWithTitle:title];
    [self startReading];
    
    if (self.incomingParam[@"companyCode"]) {
        companyCode = self.incomingParam[@"companyCode"];
        expressCompany = self.incomingParam[@"expressCompany"];
        [self.headerBtn setTitle:expressCompany];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)changeComp
{
    compArray = [PxGlobal getData:COMPANY_INFO];
    int i = 0;
    int index = 0;
    NSMutableArray *arr = [NSMutableArray new];
    for (NSDictionary *data in compArray) {
        if ([data[@"value"] isEqualToString:companyCode]) {
            index = i;
        }
        [arr addObject:data[@"label"]];
        i++;
    }
    if (!_pickViewController) {
        _pickViewController = [[PxAlertPickViewController alloc] initWithDataSource:arr];
        _pickViewController.delegate = self;
        _pickViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        _pickViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        _pickViewController.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    }
    [_pickViewController setData:index];
    [self presentViewController:_pickViewController animated:YES completion:nil];
}

- (void)buttonClick:(NSInteger)row
{
    NSDictionary *data = compArray[row];
    companyCode = data[@"value"];
    expressCompany = data[@"label"];
    [self.headerBtn setTitle:expressCompany];
    // 保存选中的值，方便下次设置默认值
    [PxGlobal saveData:companyCode andKey:COMPANY_CODE];
    [PxGlobal saveData:expressCompany andKey:COMPANY_NAME];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    _isReading = NO;
    [self stopReading];
}

@end
